package com.gamota.mobi;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Shader.TileMode;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.appota.asdk.topup.TopupAPI;

import com.devspark.appmsg.AppMsg;
import com.gamota.mobi.adapter.ContentItemAdapter;
import com.gamota.mobi.adapter.OnPopupMenuClickListener;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.db.DatabaseHelper;
import com.gamota.mobi.download.DownloadManager;
import com.gamota.mobi.download.DownloadService;
import com.gamota.mobi.download.DownloadManager.Request;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.event.Event.AllCollectionsEvent;
import com.gamota.mobi.event.Event.BuyFailEvent;
import com.gamota.mobi.event.Event.BuySuccessEvent;
import com.gamota.mobi.event.Event.GetDownloadLinkSuccess;
import com.gamota.mobi.event.Event.UserInfoSuccessEvent;
import com.gamota.mobi.model.CollectionList;
import com.gamota.mobi.model.ContentItemInfo;
import com.gamota.mobi.model.DownloadLaterItem;
import com.gamota.mobi.model.DownloadLink;
import com.gamota.mobi.model.GiftSetting;
import com.gamota.mobi.network.InstallBackgroundTask;
import com.gamota.mobi.network.ProgressDialogManager;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.StorageUtils;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.AlertDialogManager;
import com.gamota.mobi.view.ScaleImageView;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

@SuppressLint("NewApi")
public class SeeAllCollectionsActivity extends SherlockActivity implements OnItemClickListener, OnPopupMenuClickListener{
	private BackgroundTasks bgTask;
	private AQuery aq;
	private View layoutCollectionItem;
	private View layoutCollectionList;
	private LayoutInflater inflater;
	private AQuery aqCL;
	private AQuery aqCI;
	private HorizontalScrollView listItem;
	private LinearLayout parent;
	private LinearLayout collectionContainer;
	private Resources res;
	private Typeface robotoCond;
	private Typeface robotoItalic;
	private ContentItemAdapter adapter;
	private List<ContentItemInfo> listContent;
	private ListView collListItem;
	private PackageEventReceiver receiver;
	private ProgressDialog pDialog;
	private ContentItemInfo contentItem;
	private DownloadManager downloadManager;
	private DatabaseHelper db;
	private int greenTym = -1;
	private int purpleTym = -1;
	private DialogInterface.OnClickListener onClick;
	private String data, countryCode;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		setTheme(R.style.Theme_Styled_Home);
		super.onCreate(arg0);
		setContentView(R.layout.activity_coll_unit);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		EasyTracker.getInstance().setContext(this);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle(getString(R.string.collection));
		db = new DatabaseHelper(this);
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(receiver, filter);
		downloadManager = new DownloadManager(getContentResolver(), getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		countryCode = Utils.getStaticCountryCode(this);
		collListItem = (ListView) findViewById(R.id.list_coll_item);
		inflater = getLayoutInflater();
		EventBus.getDefault().register(this);
		bgTask = new BackgroundTasks(this);
		getUserInfo();
		aq = new AQuery(this);
		data = getIntent().getExtras().getString(Constants.COLLECTIONS);
		collectionContainer = (LinearLayout) findViewById(R.id.collection_unit_container);
		res = getResources();
		robotoCond = Typeface.createFromAsset(getAssets(), res.getString(R.string.roboto_condensed));
		robotoItalic = Typeface.createFromAsset(getAssets(), res.getString(R.string.roboto_italic_condensed));
		listContent = new ArrayList<ContentItemInfo>();
		adapter = new ContentItemAdapter(SeeAllCollectionsActivity.this, R.layout.short_content_item, listContent);
		adapter.setStore("apps");
		adapter.setOnPopupMenuClickListener(this);
		View layout = inflater.inflate(R.layout.collection_list_banner, null);
		ScaleImageView banner = (ScaleImageView) layout.findViewById(R.id.collection_banner);
		AQuery aqBanner = new AQuery(layout);
		aqBanner.id(banner).image(getIntent().getStringExtra(Constants.COLLECTION_COVER), true, true);
		collListItem.addHeaderView(layout);
		aq.id(collListItem).adapter(adapter);
		aq.id(collListItem).itemClicked(this);
		loadData();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(this, DownloadService.class);
		startService(intent);
	}
	
	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(this);
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
	}
	
	private void loadData(){
		bgTask.getAllCollections(data);
	}
	
	private class CustomComparator implements Comparator<CollectionList> {

		@Override
		public int compare(CollectionList obj1, CollectionList obj2) {
			// TODO Auto-generated method stub
			return obj1.getOrder() < obj2.getOrder() ? -1
			         : obj1.getOrder() > obj2.getOrder() ? 1
			         : 0;
		}
	}
	
	public void onEventMainThread(AllCollectionsEvent event){
		List<CollectionList> level2CollectionList = event.getCollectionList();
		Collections.sort(level2CollectionList, new CustomComparator());
		View layout;
		ScaleImageView banner;
		AQuery aqBanner;
		for(final CollectionList cl : level2CollectionList){
			if(cl.getOrder() % 3 == 0 && cl.getOrder() != 0){
				layout = inflater.inflate(R.layout.collection_banner, null);
				banner = (ScaleImageView) layout.findViewById(R.id.collection_banner);
				aqBanner = new AQuery(layout);
				aqBanner.id(banner).image(cl.getCover(), true, true);
				banner.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(SeeAllCollectionsActivity.this, CollectionUnitActivity.class);
						intent.putExtra(Constants.COLLECTION_LIST_ID, cl.getId());
						intent.putExtra(Constants.COLLECTION_TITLE, cl.getName());
						intent.putExtra(Constants.COLLECTION_COVER, cl.getCover());
						startActivity(intent);
					}
				});
				collectionContainer.addView(layout);
			} else {
				layoutCollectionList = inflater.inflate(R.layout.collection_list_item, null);
				layoutCollectionList.findViewById(R.id.collection_name).setSelected(true);
				aqCL = new AQuery(layoutCollectionList);
				aqCL.id(R.id.collection_name).text(cl.getName()).typeface(robotoItalic);
				aqCL.id(R.id.btn_coll_seemore).typeface(robotoCond).clicked(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(SeeAllCollectionsActivity.this, CollectionUnitActivity.class);
						intent.putExtra(Constants.COLLECTION_LIST_ID, cl.getId());
						intent.putExtra(Constants.COLLECTION_TITLE, cl.getName());
						intent.putExtra(Constants.COLLECTION_COVER, cl.getCover());
						startActivity(intent);
					}
				});
				listItem = (HorizontalScrollView) layoutCollectionList.findViewById(R.id.horiz_list_item);
				parent = new LinearLayout(this);
				parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				for(int i = 0; i < cl.getContentList().size(); i++){
					final ContentItemInfo item = cl.getContentList().get(i);
					layoutCollectionItem = inflater.inflate(R.layout.collection_item, null);
					aqCI = new AQuery(layoutCollectionItem);
					if(UILApplication.getInstance().isLoadAllImgs()){
						aqCI.id(R.id.coll_icon).visibility(View.VISIBLE);
						if(aqCI.getCachedFile(item.getAvatar())!=null){
							aqCI.id(R.id.coll_icon).image(aqCI.getCachedFile(item.getAvatar()), 75);
							Log.e("NMN","load images from CachedFile");
						}else{
							Log.e("NMN","load images from server");
							aqCI.id(R.id.coll_icon).image(item.getAvatar(), false, true, 0, 0, null, AQuery.FADE_IN_NETWORK, 1.0f/1.0f);
						}
					}else{
						aqCI.id(R.id.coll_icon).visibility(View.GONE);
					}
					
					aqCI.id(R.id.coll_name).text(item.getTitle()).typeface(robotoCond);
					int price = item.getPrice();
					if(price == 0){
						aqCI.id(R.id.coll_price).text(res.getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoCond);
					} else {
						aqCI.id(R.id.coll_price).text(String.valueOf(price)).typeface(robotoCond);
					}
					if(item.getGiftbox() == 1){
						aqCI.id(R.id.ribbon_gift).visible();
					} else {
						aqCI.id(R.id.ribbon_gift).gone();
					}
					aqCI.id(R.id.coll_rating).rating(item.getRating());
					final String slug = item.getApplicationId();
					aqCI.id(R.id.item_container).clicked(new OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(SeeAllCollectionsActivity.this, ItemBrokerActivity.class);
							intent.putExtra(Constants.PREVIOUS_SCREEN, "collection");
							intent.putExtra(Constants.SLUG, slug);
							intent.putExtra(Constants.FROM, 3);
							intent.putExtra(Constants.KEY_REFERER, "ads");
							intent.putExtra(Constants.STORE_KEY, "apps");
							startActivity(intent);
						}
					});
					aqCI.id(R.id.btn_quick_menu).clicked(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if(db.checkAppInstalled(item.getPackageName())){
								showInstalledMenu(v, item.getPackageName());
							} else {
								showNotInstalledMenu(v, item);
							}
						}
					});
					parent.addView(layoutCollectionItem);
				}
				listItem.addView(parent);
				collectionContainer.addView(layoutCollectionList);
			}
		}
		aq.id(R.id.unit_coll_progress).gone();
		aq.id(R.id.btn_retry_unit_coll).gone();
		aq.id(R.id.scroll).visible();
		aq.id(R.id.list_coll_item).gone();
	}
	
//	public void onEventMainThread(RequestFailEvent event){
//		ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
//		aq.id(R.id.unit_coll_progress).gone();
//		aq.id(R.id.btn_retry_unit_coll).visible().clicked(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				aq.id(R.id.unit_coll_progress).visible();
//				aq.id(R.id.btn_retry_unit_coll).gone();
//				collectionContainer.removeAllViews();
//				bgTask.getLevel3CollectionList(accessToken, Constants.ANDROID_STORE, listId);
//			}
//		});
//		aq.id(collectionContainer).gone();
//	}

//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		super.onResume();
//		eventBus.register(this);
//	}
//
//	@Override
//	protected void onPause() {
//		// TODO Auto-generated method stub
//		super.onPause();
//		eventBus.unregister(this);
//	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
		EventBus.getDefault().unregister(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		if(v.getTag() == null){
			return;
		}
		ContentItemInfo item = (ContentItemInfo) parent.getItemAtPosition(pos);
		Intent intent = new Intent(SeeAllCollectionsActivity.this, ItemBrokerActivity.class);
		intent.putExtra(Constants.PREVIOUS_SCREEN, "collection");
		intent.putExtra(Constants.SLUG, item.getApplicationId());
		intent.putExtra(Constants.FROM, 3);
		intent.putExtra(Constants.KEY_REFERER, "ads");
		intent.putExtra(Constants.STORE_KEY, "apps");
		startActivity(intent);
	}
	
	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				String packageName = "";
				for(ContentItemInfo item : listContent){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(installedName)){
						item.setInstalled(true);
					}
				}
				adapter.notifyDataSetChanged();
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String packageName = "";
				String uninstalledName = intent.getDataString().split(":")[1];
				for(ContentItemInfo item : listContent){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(uninstalledName)){
						item.setInstalled(false);
					}
				}
				adapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onInstallClicked(String store, final ContentItemInfo item) {
		// TODO Auto-generated method stub
		this.contentItem = item;
		if(!countryCode.equalsIgnoreCase("vn")){
			Intent gp = new Intent(Intent.ACTION_VIEW);
			gp.setData(Uri.parse(item.getRootLink()));
			startActivity(gp);
		} else {
			if(checkLogin()){
				if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showWebViewDialog(aq, item.getInstallAttachApplication(), SeeAllCollectionsActivity.this, item.getPermission(), R.string.app_permissions, item.getAttachApplicationAvatar(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String accessToken = Utils.getStaticAccessToken(SeeAllCollectionsActivity.this);
							pDialog = ProgressDialogManager.showProgressDialog(SeeAllCollectionsActivity.this, R.string.loading);
							bgTask.buyContent("",accessToken, item.getApplicationId(), 0);
							dialog.dismiss();
						}
					});
				} else {
					String accessToken = Utils.getStaticAccessToken(SeeAllCollectionsActivity.this);
					pDialog = ProgressDialogManager.showProgressDialog(SeeAllCollectionsActivity.this, R.string.loading);
					bgTask.buyContent("",accessToken, item.getApplicationId(), 0);
				}
			} else {
				AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
				am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
//							Intent intent = new Intent(SeeAllCollectionsActivity.this, LoginActivity.class);
//							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//							startActivity(intent);
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			}
		}
	}

	@Override
	public void onAddToWishListClicked(String store, ContentItemInfo item) {
		// TODO Auto-generated method stub
		DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
		dlItem.setPrice1(item.getPrice());
		dlItem.setPrice2(item.getPrice2());
		dlItem.setPackageName(item.getPackageName());
		dlItem.setType(store);
		boolean added = db.addDownloadLater(dlItem);
		if(added){
			Toast.makeText(this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onDownloadClicked(String store, ContentItemInfo item) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLaunchClicked(String packageName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onWatchClicked(ContentItemInfo item) {
		// TODO Auto-generated method stub
		
	}
	
	private void showInstalledMenu(View v, final String packageName){
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			PopupMenu menu = new PopupMenu(this, v);
			menu.getMenuInflater().inflate(R.menu.installed_app_menu, menu.getMenu());
			menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(android.view.MenuItem menuItem) {
					// TODO Auto-generated method stub
					switch (menuItem.getItemId()) {
					case R.id.menu_launch:
						Intent launch = getPackageManager().getLaunchIntentForPackage(packageName);
						launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(launch);
						break;
					case R.id.menu_uninstall:
						Utils.uninstallAPK(SeeAllCollectionsActivity.this, packageName);
						break;
					}
					return true;
				}
			});
			menu.show();
		} else {
			main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(this);
			popupMenuCompat.add(1, R.string.menu_launch);
			popupMenuCompat.add(2, R.string.menu_uninstall);
			popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
					switch (menuItem.getItemId()) {
					case 1:
						Intent launch = getPackageManager().getLaunchIntentForPackage(packageName);
						launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(launch);
						break;
					case 2:
						Utils.uninstallAPK(SeeAllCollectionsActivity.this, packageName);
						break;
					}
				}
			});
			popupMenuCompat.show(v);
		}
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(this);
	}
	
	private void download(ContentItemInfo item){
		pDialog = ProgressDialogManager.showProgressDialog(SeeAllCollectionsActivity.this, R.string.loading);
		if(item.getPrice() != 0){
			validAndBuy(item.getPrice(), "green", item, 0);
		} else if(item.getPrice2() != 0){
			validAndBuy(item.getPrice2(), "purple", item, 0);
		} else {
			validAndBuy(0, "free", item, 0);
		}
	}
	
	private void showNotInstalledMenu(View v, final ContentItemInfo item){
		this.contentItem = item;
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			PopupMenu menu = new PopupMenu(this, v);
			menu.getMenuInflater().inflate(R.menu.not_installed_app_menu,menu.getMenu());
			menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(android.view.MenuItem menuItem) {
					// TODO Auto-generated method stub
					switch (menuItem.getItemId()) {
					case R.id.menu_install:
						if(checkLogin()){
							checkGift();
						} else {
							AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
							am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									switch (which) {
									case DialogInterface.BUTTON_POSITIVE:
//										Intent intent = new Intent(SeeAllCollectionsActivity.this, LoginActivity.class);
//										intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//										startActivity(intent);
										break;
									case DialogInterface.BUTTON_NEGATIVE:
										dialog.dismiss();
										break;
									}
								}
							});
						}
						break;
					case R.id.menu_add_wishlist:
						DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
						dlItem.setPrice1(item.getPrice());
						dlItem.setPrice2(item.getPrice2());
						dlItem.setPackageName(item.getPackageName());
						dlItem.setType("apps");
						boolean added = db.addDownloadLater(dlItem);
						if(added){
							Toast.makeText(SeeAllCollectionsActivity.this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(SeeAllCollectionsActivity.this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
						}
						break;
					}
					return true;
				}
			});
			menu.show();
		} else {
			main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(SeeAllCollectionsActivity.this);
			popupMenuCompat.add(1, R.string.install);
			popupMenuCompat.add(2, R.string.add_to_wishlist);
			popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
					switch (menuItem.getItemId()) {
					case 1:
						if(checkLogin()){
							checkGift();
						} else {
							AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
							am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									switch (which) {
									case DialogInterface.BUTTON_POSITIVE:
//										Intent intent = new Intent(SeeAllCollectionsActivity.this, LoginActivity.class);
//										intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//										startActivity(intent);
										break;
									case DialogInterface.BUTTON_NEGATIVE:
										dialog.dismiss();
										break;
									}
								}
							});
						}
						break;
					case 2:
						//DatabaseHelper db = new DatabaseHelper(SeeAllCollectionsActivity.this);
						DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
						dlItem.setPrice1(item.getPrice());
						dlItem.setPrice2(item.getPrice2());
						dlItem.setPackageName(item.getPackageName());
						dlItem.setType(Constants.ANDROID_STORE);
						boolean added = db.addDownloadLater(dlItem);
						if(added){
							Toast.makeText(SeeAllCollectionsActivity.this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(SeeAllCollectionsActivity.this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
						}
						break;
					}
				}
			});
			popupMenuCompat.show(v);
		}
	}
	
	private void validAndBuy(int price, String tymType, ContentItemInfo item, int versionId){
		if(item.getBought() == 1){
			if(pDialog == null){
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			}
			bgTask.buyContent("",Utils.getStaticAccessToken(this), item.getApplicationId(), versionId);
		} else {
			if(tymType.equals("green")){
				if(greenTym < price && greenTym != -1){
					AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(SeeAllCollectionsActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(SeeAllCollectionsActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(greenTym == -1){
					AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
//					Intent intent = new Intent(SeeAllCollectionsActivity.this, ConfirmBuyActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
//					bundle.putString(Constants.KEY_NAME, item.getTitle());
//					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
//					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
//					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
//					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
//					bundle.putString(Constants.KEY_EP, "");
//					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
//					intent.putExtras(bundle);
//					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("purple")){
				if(purpleTym < price && purpleTym != -1){
					AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(SeeAllCollectionsActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(SeeAllCollectionsActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(purpleTym == -1){
					AlertDialogManager am = new AlertDialogManager(SeeAllCollectionsActivity.this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
//					Intent intent = new Intent(SeeAllCollectionsActivity.this, ConfirmBuyActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
//					bundle.putString(Constants.KEY_NAME, item.getTitle());
//					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
//					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
//					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
//					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
//					bundle.putString(Constants.KEY_EP, "");
//					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
//					intent.putExtras(bundle);
//					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("free")){
				bgTask.buyContent("home", Utils.getStaticAccessToken(SeeAllCollectionsActivity.this), item.getApplicationId(), versionId);
			}
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		if(event.getTopType().equalsIgnoreCase("home")){
			String accessToken = Utils.getStaticAccessToken(SeeAllCollectionsActivity.this);
			bgTask.getDownloadLink("home", accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(SeeAllCollectionsActivity.this), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(event.getTopType().equalsIgnoreCase("home")){
			if(pDialog != null){
				pDialog.dismiss();
			}
			AppMsg.makeText(SeeAllCollectionsActivity.this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		}
	}
	
	private void checkGift(){
		if(contentItem.getGiftbox() == 1){
			AlertDialogManager am = new AlertDialogManager(this);
			final DatabaseHelper db = new DatabaseHelper(this);
			GiftSetting gift = db.getGiftSync(contentItem.getApplicationId());
			if(gift != null && gift.getReceived() == 1){
				download(contentItem);
			} else {
				if(contentItem.getGiftboxDaysToGet() == 0){
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(0);
					gs.setSlug(contentItem.getApplicationId());
					gs.setAppName(contentItem.getTitle());
					gs.setName(contentItem.getPackageName());
					gs.setPicture(contentItem.getAvatar());
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							download(contentItem);
							db.addGift(gs);
						}
					};
					am.showGiftDialog(R.string.gift_message, 0, onClick);
				} else {
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(contentItem.getGiftboxDaysToGet());
					gs.setName(contentItem.getPackageName());
					gs.setSlug(contentItem.getApplicationId());
					gs.setAppName(contentItem.getTitle());
					gs.setPicture(contentItem.getAvatar());
					gs.setTimeToReceive(Utils.calculateDaysToGetGift(contentItem.getGiftboxDaysToGet()));
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							download(contentItem);
							db.addGift(gs);
						}
					};
					am.showGiftDialog(R.string.gift_message_days, contentItem.getGiftboxDaysToGet(), onClick);
				}
			}
		} else {
			download(contentItem);
		}
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase("home")){
			if(pDialog != null){
				pDialog.dismiss();
			}
			if(contentItem.getInstallAttachApplication() == 1){
				String accessToken = Utils.getStaticAccessToken(this);
				bgTask.buyAttachedContent(accessToken, contentItem.getAttachApplicationSlug(), 0);
			}
				DownloadLink download = event.getDl();
				List<String> extraUrls = download.getExtraDownloads();
				if(extraUrls.size() > 0){
					for(String extraUrl : extraUrls){
						Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
						DownloadManager.Request request = new Request(srcUri);
						if(extraUrl.endsWith("obb")){
							String obbDir = StorageUtils.OBB_ROOT + contentItem.getPackageName() + "/";
							File obb = new File(obbDir);
							if(!obb.exists()){
								obb.mkdirs();
							}
							request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
						} else {
							request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
						}
						request.setTitle(String.format(getResources().getString(R.string.additional_file), contentItem.getTitle()));
						request.setDescription(contentItem.getAvatar());
						request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
						downloadManager.enqueue(request);
					}
				}
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setTitle(contentItem.getTitle());
				request.setDescription(contentItem.getAvatar());
				setDownloadData(request, url);
				downloadManager.enqueue(request);
		}
	}
	
	private void setDownloadData(Request request, String url){
		request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
		request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getMessage() != null){
			if(e.getMessage().contains("exist")){
				AlertDialogManager am = new AlertDialogManager(this);
				am.showFileDowloadDialog("apps", R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							boolean autoInstall = PreferenceManager.getDefaultSharedPreferences(SeeAllCollectionsActivity.this).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
				    		if(!autoInstall){
				    			Utils.installAPK(SeeAllCollectionsActivity.this, StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
				    		} else {
				    			InstallBackgroundTask task = new InstallBackgroundTask(SeeAllCollectionsActivity.this);
				    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), contentItem.getTitle());
				    		}
							break;
						case DialogInterface.BUTTON_NEGATIVE:
//							DeleteFileTask task = new DeleteFileTask(SeeAllCollectionsActivity.this, false);
//							task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
							Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
							break;
						case DialogInterface.BUTTON_NEUTRAL:
							dialog.dismiss();
							break;
						}
					}
				});
			} else {
				AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
			}
		}
		downloadManager.remove(e.getId());
	}
}
